package com.txtsqlclient.ui;

/**
 * This class attempts to erase characters echoed to the console. Refer to this page for more
 * details: http://java.sun.com/developer/technicalArticles/Security/pwordmask/
 */

class MaskingThread extends Thread {

    private volatile boolean mask = true;

    private char echochar = '*';

    /**
     * @param prompt
     *            The prompt displayed to the user
     */
    public MaskingThread(String prompt) {
        System.out.print(prompt);
    }

    /**
     * Begin masking until asked to stop.
     */
    @Override
    public void run() {

        int priority = Thread.currentThread().getPriority();
        Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

        try {
            this.mask = true;
            while (this.mask) {
                System.out.print("\010" + this.echochar);
                // attempt masking at this rate
                Thread.currentThread().sleep(1);
            }
        } catch (InterruptedException iex) {
            Thread.currentThread().interrupt();
            return;
        } finally { // restore the original priority
            Thread.currentThread().setPriority(priority);
        }
    }

    /**
     * Instruct the thread to stop masking.
     */
    public void stopMasking() {
        this.mask = false;
    }

    public void startMasking() {
        this.mask = true;
    }
}